package biz.yfsoft.app.fastframework.interceptor;

import java.util.Map;

import biz.yfsoft.app.fastframework.bo.Bo;
import biz.yfsoft.app.fastframework.core.BaseFastController;
import biz.yfsoft.app.fastframework.core.Fast;
import biz.yfsoft.app.fastframework.kit.IPKit;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class BehaviorInterceptor implements Interceptor {

	@Override
	public void intercept(ActionInvocation ai) {
		Controller ctr = ai.getController();
		if(! (ctr instanceof BaseFastController)){
			ai.invoke();
			return;
		}
		final BaseFastController ac = (BaseFastController)ai.getController();
		
		final boolean flag = ac.invokeResult;
		final String failReason = ac.failReason;
		final String ak = ai.getActionKey();
		final Record user = ac.getCurrentUser();
		String ip = null;
		Object uid = null;
		if(null == user){
			ip = IPKit.getRemoteLoginUserIp(ac.getRequest());
			uid = 0;
		}else{
			ip = user.get("ip");
			uid = user.get("id");
		}
		Map<String,String> args = null;
		//如果是支付回调则将参数进行url解码
		if(ak.endsWith("payNotify")){
			args = ac.getStringParams();
		}else{
			args = ac.getStringParams();
		}
		ai.invoke();
		if(Fast.me().checkBehavior(ak)){
			//log the behavior
			final String theIP = ip;
			final Object theUid = uid;
			final Map<String,String> arg = args;
			Fast.AynTask(new Runnable(){
	
				@Override
				public void run() {
					Bo bo = new Bo();
					bo.set("action",Fast.me().getBehavior(ak).get("title")+""+(flag?" SUCCESS":" ERROR"));
					bo.set("ip",theIP);
					bo.set("result",flag?1:0);
					if(!flag){
						//fail
						bo.set("reason",failReason);
					}
					bo.set("user",theUid);
					bo.set("args", arg.toString());
					
					Object tempO = Fast.me().getBehavior(ak).get("webhook");
					if(StrKit.notNull(tempO)){
						Fast.AynWebHook(tempO.toString(),arg);
					}
					bo.create();
					Db.save("sys_log", bo);
				}
				
			});
		}
	}

}
